﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

namespace NetBay.Core.BusinessEntities.Workflow.Rules
{
    [XmlTypeAttribute(AnonymousType = true)]
    [XmlRootAttribute(ElementName = "Rules", Namespace = "", IsNullable = false)]
    [Serializable]
    public class Rules
    {
        public Rules()
        {
            UseGlobalActionOnly = false;
        }

        /// <summary>
        /// Gets or sets the use global action only.
        /// </summary>
        /// <value>The use global action only.</value>
        [XmlAttributeAttribute()]
        public bool UseGlobalActionOnly { get; set; }

        /// <summary>
        /// Gets or sets the WkfStates.
        /// </summary>
        /// <value>The conditions.</value>
        [XmlArray("WkfStates", IsNullable = false)]
        [XmlArrayItem("WkfState")]
        public ObservableCollection<WkfState> WkfStates { get; set; }

        /// <summary>
        /// Serializes this instance.
        /// </summary>
        /// <returns></returns>
        public string Serialize()
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Rules));
                serializer.Serialize(memoryStream, this);

                memoryStream.Seek(0, SeekOrigin.Begin);

                using (StreamReader streamReader = new StreamReader(memoryStream))
                {
                    return streamReader.ReadToEnd();
                }
            }
        }

        /// <summary>
        /// Loads from file.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns></returns>
        public static Rules LoadFromFile(string fileName)
        {
            using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader sr = new StreamReader(file))
                {
                    string xmlString = sr.ReadToEnd();

                    return Deserialize(xmlString);
                }
            }
        }

        /// <summary>
        /// Deserializes the specified XML.
        /// </summary>
        /// <param name="xml">The XML.</param>
        /// <returns></returns>
        public static Rules Deserialize(string xml)
        {
            using (StringReader stringReader = new StringReader(xml))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Rules));

                return ((Rules)(serializer.Deserialize(XmlReader.Create(stringReader))));
            }
        }
    }
}
